package cn.uway.health;


import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.stereotype.Component;

import cn.uway.properties.RedisProperties;

import redis.clients.jedis.Client;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;

@Component("redisHealthIndicator")
public class MyRedisHealthIndicator extends AbstractHealthIndicator {
	
	protected  Logger logger = LoggerFactory.getLogger(this.getClass());	

	@Autowired
	private  JedisPool  jedisPool;
	
	@Autowired
	private  RedisProperties redisProperties;
	
	@Override
	protected void doHealthCheck(Health.Builder builder) throws Exception {
		builder.withDetail("host", redisProperties.getHost());
		builder.withDetail("port", redisProperties.getPort());
		
		Jedis jedis = jedisPool.getResource();	
		Client client = jedis.getClient();
		client.info();
		Map<String,Object> map = new HashMap<String,Object>();
    	String info = client.getBulkReply();
    	if(info!=null && !"".equals(info)){
    		String[] array = info.split("\r\n");
    		for(String item : array){
    			if(!"".equals(item) && !item.startsWith("#") && item.contains(":")){
    				String[] tmp = item.split(":");
    				if(tmp.length==2){
    					map.put(tmp[0], tmp[1]);
    				}					
    			}
    		}
    	}
		builder.up().withDetail("version", map.get("redis_version") );
		if(jedis!=null){
			 try{
				 jedis.close();
			 }
			 catch (JedisConnectionException e) {
				 logger.error("release jedis err", e);
			 }			
		 }
	}

}
